<?php

declare(strict_types=1);

include_once './vendor/autoload.php';

use Swow\Coroutine;
use Swow\Psr7\Client\Client;
use Swow\Psr7\Psr7;

function http_get(int $id): array
{
    $domain = 'httpbin.org';
    $url = '/get';
    $method = 'GET';
    $body = null;
    $headers = [
        "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding" => "gzip, deflate",
        "Accept-Language" => "zh-CN,zh;q=0.9",
        "Host" => "httpbin.org",
        "Upgrade-Insecure-Requests" => "1",
        "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",
        "X-Amzn-Trace-Id" => "Root=1-64aba9f1-21d3b7fc74c92f406c6a20a1"
    ];
    $client = new Client();
    $request = Psr7::createRequest(method: $method, uri: $url, headers: $headers, body: $body);
    try {
        $response = $client
            ->connect($domain, 80)
            ->sendRequest($request);
        $result = Psr7::stringifyResponse($response);
        return [
            'id'=>$id,
            'time'=>date('Y-m-d H:i:s'),
            'code'=>$response->getStatusCode(),
//            'body'=>$response->getBody()->getContents(),
//            'data'=>$result,
        ];
    } catch (\Psr\Http\Client\ClientExceptionInterface $e) {
        var_dump($e);
        return [];
    }
}
use Swow\Sync\WaitReference;

$wr = new WaitReference();
for ($c = 0; $c < 10; $c++) {
    Coroutine::run(static function () use ($c, $wr): void {
        $res = http_get($c);
        var_dump($res);
    });
}

echo "Wait...\n";
$wr::wait($wr);
echo "Done\n";
